<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>活动列表</title>
    <link rel="stylesheet" type="text/css" th:href="@{/easyui/themes/default/easyui.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/easyui/themes/icon.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/easyui/css/demo.css}">
    <script type="text/javascript" th:src="@{/easyui/jquery.min.js}"></script>
    <script type="text/javascript" th:src="@{/easyui/jquery.easyui.min.js}"></script>
    <script type="text/javascript" th:src="@{/easyui/js/validateExtends.js}"></script>
    <script type="text/javascript" th:inline="javascript">
        /*<![CDATA[*/
        function setInitialStatus(status) {
            if (status === 1) {
                document.getElementById("statusOpen").checked = true;
            } else if (status === 0) {
                document.getElementById("statusClosed").checked = true;
            }
        }

        // 向后端发送状态更新请求
        function updateStatus(status) {
            fetch('/activity/updateStatus', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ status: status }),
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('状态更新成功');
                    } else {
                        alert('状态更新失败');
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('请求失败');
                });
        }
        $(function() {
            //datagrid初始化
            $('#dataList').datagrid({
                title:'活动列表',
                iconCls:'icon-more',//图标
                border: true,
                collapsible:false,//是否可折叠的
                fit: true,//自动大小
                method: "post",
                url:[[@{/activity/getActivityList}]],
            idField:'id',
                singleSelect:false,//是否单选
                pagination:true,//分页控件
                rownumbers:true,//行号
                sortName:'id',
                sortOrder:'DESC',
                remoteSort: false,
                columns: [
                [
                    {field:'chk',checkbox: true,width:50},
                    {field:'id',title:'ID',width:50, sortable: true},
                    {field:'name',title:'活动名',width:200, sortable: true},
                    {field:'category',title:'活动类型',width:200},
                    {field:'title',title:'活动全称',width:100},
                    {field:'creator',title:'活动创建者',width:150},
                    {field:'status',title:'状态',width:150},
                    {field:'abstractText',title:'活动摘要',width:150},
                    {field:'detailedDesc',title:'活动详细内容',width:150},
                    {field:'archivedTime',title:'活动归档时间',width:150},
                    {field:'startTime',title:'活动开始时间',width:150},
                    {field:'endTime',title:'活动结束时间',width:150},
                    {field:'createdTime',title:'活动创建时间',width:150,
                        formatter: function(value,row,index){
                            if (row.clazzId){
                                var clazzList = $("#clazzList").combobox("getData");
                                for(var i=0;i<clazzList.length;i++ ){
                                    //console.log(clazzList[i]);
                                    if(row.clazzId == clazzList[i].id)return clazzList[i].name;
                                }
                                return row.clazzId;
                            } else {
                                return 'not found';
                            }
                        }
                    },

                ]
            ],
                toolbar: "#toolbar",
                onBeforeLoad : function(){
                try{
                    $("#clazzList").combobox("getData")
                }catch(err){
                    preLoadClazz();
                }
            }
        });
            //设置分页控件
            var p = $('#dataList').datagrid('getPager');
            $(p).pagination({
                pageSize: 10,//每页显示的记录条数，默认为10
                pageList: [10,20,30,50,100],//可以设置每页记录条数的列表
                beforePageText: '第',//页数文本框前显示的汉字
                afterPageText: '页    共 {pages} 页',
                displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录',
            });
            //设置工具类按钮
            $("#add").click(function(){
                $("#addDialog").dialog("open");
            });
            //修改
            $("#edit").click(function(){
                var selectRows = $("#dataList").datagrid("getSelections");
                if(selectRows.length != 1){
                    $.messager.alert("消息提醒", "请选择一条数据进行操作!", "warning");
                } else{
                    $("#editDialog").dialog("open");
                }
            });
            //删除
            $("#delete").click(function(){
                var selectRows = $("#dataList").datagrid("getSelections");
                var selectLength = selectRows.length;
                if(selectLength == 0){
                    $.messager.alert("消息提醒", "请选择数据进行删除!", "warning");
                } else{
                    var jsonObj = {};
                    $.each(selectRows,function(i,n){
                        jsonObj["ids["+i+"]"] = n.id;
                    });
                    $.messager.confirm("消息提醒", "将删除与学生相关的所有数据(包括成绩)，确认继续？", function(r){
                        if(r){
                            $.ajax({
                                type: "post",
                                url: [[@{/activity/deleteActivity}]],
                            data:jsonObj,
                                success: function(data){
                                if(data.success){
                                    $.messager.alert("消息提醒",data.message,"info");
                                    //刷新表格
                                    $("#dataList").datagrid("reload");
                                    $("#dataList").datagrid("uncheckAll");
                                } else{
                                    $.messager.alert("消息提醒",data.message,"warning");
                                    return;
                                }
                            }
                        });
                        }
                    });
                }
            });


            function preLoadClazz(){
                $("#clazzList").combobox({
                    width: "150",
                    height: "25",
                    valueField: "id",
                    textField: "name",
                    multiple: false, //可多选
                    editable: false, //不可编辑
                    method: "post",
                    url: [[@{/activity/activity_list}]],
                onChange: function(newValue, oldValue){
                    //加载班级下的学生
                    //$('#dataList').datagrid("options").queryParams = {clazzid: newValue};
                    //$('#dataList').datagrid("reload");
                }
            });
            }

            //下拉框通用属性
            $("#add_clazzList, #edit_clazzList").combobox({
                width: "200",
                height: "30",
                valueField: "id",
                textField: "name",
                multiple: false, //可多选
                editable: false, //不可编辑
                method: "post",
            });


            $("#add_clazzList").combobox({
                url: [[@{/clazz/getClazzList(from=combox)}]],
            onLoadSuccess: function(){
                //默认选择第一条数据
                var data = $(this).combobox("getData");;
                $(this).combobox("setValue", data[0].id);
            }
        });



            $("#edit_clazzList").combobox({
                url: [[@{/clazz/getClazzList(from=combox)}]],
            onLoadSuccess: function(){
                //默认选择第一条数据
                var data = $(this).combobox("getData");
                $(this).combobox("setValue", data[0].id);
            }
        });

            //设置添加学生窗口
            $("#addDialog").dialog({
                title: "添加学生",
                width: 650,
                height: 460,
                iconCls: "icon-add",
                modal: true,
                collapsible: false,
                minimizable: false,
                maximizable: false,
                draggable: true,
                closed: true,
                buttons: [
                    {
                        text:'添加',
                        plain: true,
                        iconCls:'icon-user_add',
                        handler:function(){
                            var validate = $("#addForm").form("validate");
                            if(!validate){
                                $.messager.alert("消息提醒","请检查你输入的数据!","warning");
                                return;
                            } else{
                                var formData = new FormData($( "#addForm" )[0]);
                                $.ajax({
                                    type: "post",
                                    url: [[@{/activity/addActivity}]],
                                data: formData,
                                    async: false,
                                    cache: false,
                                    contentType: false,
                                    processData: false,
                                    success: function(data){
                                    if(data.success){
                                        $.messager.alert("消息提醒",data.message,"info");
                                        //关闭窗口
                                        $("#addDialog").dialog("close");
                                        //清空原表格数据
                                        $("#add_number").textbox('setValue', "");
                                        $("#add_name").textbox('setValue', "");
                                        $("#add_sex").textbox('setValue', "男");
                                        $("#add_phone").textbox('setValue', "");
                                        $("#add_qq").textbox('setValue', "");

                                        //重新刷新页面数据
                                        $('#dataList').datagrid("options").queryParams = {clazzid: clazzid};
                                        $('#dataList').datagrid("reload");
                                        setTimeout(function(){
                                            $("#clazzList").combobox('setValue', clazzid);
                                        }, 100);

                                    } else{
                                        $.messager.alert("消息提醒",data.message,"warning");
                                        return;
                                    }
                                }
                            });
                            }
                        }
                    },
                    {
                        text:'重置',
                        plain: true,
                        iconCls:'icon-reload',
                        handler:function(){
                            $("#add_number").textbox('setValue', "");
                            $("#add_name").textbox('setValue', "");
                            $("#add_phone").textbox('setValue', "");
                            $("#add_qq").textbox('setValue', "");
                            //重新加载年级
                            $("#add_gradeList").combobox("clear");
                            $("#add_gradeList").combobox("reload");
                        }
                    },
                ]
            });

            //设置编辑学生窗口
            $("#editDialog").dialog({
                title: "修改学生信息",
                width: 650,
                height: 460,
                iconCls: "icon-edit",
                modal: true,
                collapsible: false,
                minimizable: false,
                maximizable: false,
                draggable: true,
                closed: true,
                buttons: [
                    {
                        text:'提交',
                        plain: true,
                        iconCls:'icon-user_add',
                        handler:function(){
                            var validate = $("#editForm").form("validate");
                            var clazzid = $("#edit_clazzList").combobox("getValue");
                            if(!validate){
                                $.messager.alert("消息提醒","请检查你输入的数据!","warning");
                                return;
                            } else{
                                var formData = new FormData($( "#editForm" )[0]);
                                $.ajax({
                                    type: "post",
                                    url: [[@{/activity/editActivity}]],
                                data: formData,
                                    async: false,
                                    cache: false,
                                    contentType: false,
                                    processData: false,
                                    success: function(data){
                                    if(data.success){
                                        $.messager.alert("消息提醒",data.message,"info");
                                        //关闭窗口
                                        $("#editDialog").dialog("close");
                                        //刷新表格
                                        $('#dataList').datagrid("options").queryParams = {clazzid: clazzid};
                                        $("#dataList").datagrid("reload");
                                        $("#dataList").datagrid("uncheckAll");

                                        setTimeout(function(){
                                            $("#clazzList").combobox('setValue', clazzid);
                                        }, 100);

                                    } else{
                                        $.messager.alert("消息提醒",data.message,"warning");
                                        return;
                                    }
                                }
                            });
                            }
                        }
                    },
                    {
                        text:'重置',
                        plain: true,
                        iconCls:'icon-reload',
                        handler:function(){
                            //清空表单
                            $("#imgd div").remove();
                            $("#edit_name").textbox('setValue', "");
                            $("#edit_sex").textbox('setValue', "男");
                            $("#edit_phone").textbox('setValue', "");
                            $("#edit_qq").textbox('setValue', "");
                            $("#edit_gradeList").combobox("clear");
                            $("#edit_gradeList").combobox("reload");
                        }
                    }
                ],
                onBeforeOpen: function(){
                    var selectRow = $("#dataList").datagrid("getSelected");
                    $("#imgd div").remove();
                    $.ajax({
                        type: "post",
                        url: [[@{/system/getPhoto}]]+"?sid="+selectRow.id,
                        success: function(data){
                        var i = [[@{/upload/imgs/}]];
                        var imgUrl = data.imgurl;
                        var img = i + imgUrl;
                        //设置值
                        $("#edit_name").textbox('setValue', selectRow.activityname);
                        $("#edit_sex").textbox('setValue', selectRow.sex);
                        $("#edit_mobile").textbox('setValue', selectRow.mobile);
                        $("#edit_qq").textbox('setValue', selectRow.qq);

                        var div = document.createElement("div"),
                            img1 = document.createElement("img");
                        //div.className = "pic";
                        img1.src=img;
                        $(img1).css("width","200px");
                        $(img1).css("hight","200px");
                        div.appendChild(img1);
                        $("#imgd").append(div);

                        //$("#edit_photo").attr("src", img);
                        // $(".imgDiv").

                        $("#edit-id").val(selectRow.id);
                        $("#set-photo-id").val(selectRow.id);
                        var clazzid = selectRow.clazzId;
                        setTimeout(function(){
                            $("#edit_clazzList").combobox('setValue', clazzid);
                        }, 100);
                    }
                    });
                }
                });
            //搜索按钮监听事件
            $("#search-btn").click(function(){
                $('#dataList').datagrid('load',{
                    studentName: $('#search_student_name').val(),
                    clazzid: $("#clazzList").combobox('getValue') == '' ? 0 : $("#clazzList").combobox('getValue')
                });
            });
        });
            //上传图片按钮事件
            $("#upload-photo-btn").click(function(){

            });

            /*图片预览*/
            var filechange=function(event){
                $("#imgDiv div").remove();

                var inp = event.path[0];
                var files = event.target.files;
                $.each(files,function(key,value){
                    //每次都只会遍历一个图片数据
                    var div = document.createElement("div"),
                        img = document.createElement("img");
                    div.className = "pic";

                    var fr = new FileReader();
                    fr.onload = function(){
                        img.src=this.result;
                        $(img).css("width","200px");
                        $(img).css("hight","200px");
                        div.appendChild(img);
                        $("#imgDiv").append(div);
                    };
                    console.log(img)
                    fr.readAsDataURL(value);
                })
            };

            var filechange1=function(event){
                $("#imgd div").remove();

                var inp = event.path[0];
                var files = event.target.files;
                $.each(files,function(key,value){
                    //每次都只会遍历一个图片数据
                    var div = document.createElement("div"),
                        img = document.createElement("img");
                    div.className = "pic";

                    var fr = new FileReader();
                    fr.onload = function(){
                        img.src=this.result;
                        $(img).css("width","200px");
                        $(img).css("hight","200px");
                        div.appendChild(img);
                        $("#imgd").append(div);
                    };
                    console.log(img)
                    fr.readAsDataURL(value);
                })
            };


        /*]]>*/
    </script>
</head>
<body>
<!-- 学生列表 -->
<table id="dataList" cellspacing="0" cellpadding="0">

</table>
<!-- 工具栏 -->
<div id="toolbar">
    <div th:if="${session.usertype == '1' || session.usertype == '3'}" style="float: left;"><a id="add" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true">添加</a></div>
    <div th:if="${session.usertype == '1' || session.usertype == '3'}" style="float: left;" class="datagrid-btn-separator"></div>
    <div style="float: left;"><a id="edit" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-edit',plain:true">修改</a></div>
    <div style="float: left;" class="datagrid-btn-separator"></div>
    <div th:if="${session.usertype == '1' || session.usertype == '3'}" style="float: left;"><a id="delete" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-some-delete',plain:true">删除</a></div>
    <div style="float: left;margin-top:4px;" class="datagrid-btn-separator" >&nbsp;&nbsp;姓名：<input id="search_student_name" class="easyui-textbox" name="search_student_name" /></div>
    <div style="margin-left: 10px;margin-top:4px;" >班级：<input id="clazzList" class="easyui-textbox" name="clazz" />
        <a id="search-btn" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true">搜索</a>
    </div>

</div>

<!-- 添加学生窗口 -->
<div id="addDialog" style="padding: 10px">

    <form id="addForm" method="post" enctype="multipart/form-data">
        <table cellpadding="8" >

            <tr>
                <td>活动名:</td>
                <td><input id="add_name" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="activityname" data-options="required:true, missingMessage:'请填写活动名'" /></td>
            </tr>
            <tr>
                <td>活动类型 :</td>
                <td>
                    <input id="add_category"  class="easyui-textbox" style="width: 200px; height: 30px;" type="text" name="category" data-options="required:true, missingMessage:'请输入活动类型'" />
                </td>
            </tr>
            <tr>
                <td>活动全称:</td>
                <td><input id="add_title" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="title"/></td>
            </tr>
            <tr>
                <td>活动创建者:</td>
                <td><input id="add_creator" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="creator"/></td>
            </tr>
            <tr>
                <td>状态:</td>
                <td><input id="add_status" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="status"/></td>
            </tr>
            <tr>
                <td>活动摘要:</td>
                <td><input id="add_abstract" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="abstract"/></td>
            </tr>
            <tr>
                <td>活动详细内容:</td>
                <td><input id="add_detailed" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="detailed"/></td>
            </tr>
            <tr>
                <td>活动开始时间:</td>
                <td><input id="add_starttime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="starttime"/></td>
            </tr>
            <tr>
                <td>活动结束时间:</td>
                <td><input id="add_endtime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="endtime"/></td>
            </tr>
            <tr>
                <td>活动归档时间:</td>
                <td><input id="add_archivedtime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="archivedtime"/></td>
            </tr>
            <tr>
                <td>相片:</td>
                <td><input onchange="filechange(event)" type="file" name="file" multiple></td>
                <td><div id="imgDiv"></div></td>
            </tr>
        </table>
    </form>
</div>

<!-- 修改学生窗口 -->
<div id="editDialog" style="padding: 10px">
    <!--	<div style="float: right; margin: 20px 20px 0 0; width: 200px; border: 1px solid #EBF3FF">-->
    <!--		<img id="edit_photo" alt="照片" style="max-width: 200px; max-height: 400px;" title="照片" src="" />-->
    <!--		<form id="uploadForm" method="post" enctype="multipart/form-data" action="PhotoServlet?method=SetPhoto" target="photo_target">-->
    <!--			&lt;!&ndash; StudentServlet?method=SetPhoto &ndash;&gt;-->
    <!--			<input type="hidden" name="sid" id="set-photo-id">-->
    <!--			<input class="easyui-filebox" name="photo" data-options="prompt:'选择照片'" style="width:200px;">-->
    <!--			<input id="upload-photo-btn" onClick="uploadPhoto()" class="easyui-linkbutton" style="width: 50px; height: 24px;" type="button" value="上传"/>-->
    <!--		</form>-->
    <!--	</div>-->
    <form id="editForm" method="post" enctype="multipart/form-data">
        <input type="hidden" name="id" id="edit-id">
        <table cellpadding="8" >

            <tr>
                <td>活动名:</td>
                <td><input id="edit_name" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="activityname" data-options="required:true, missingMessage:'请填写活动名'" /></td>
            </tr>
            <tr>
                <td>活动类型 :</td>
                <td>
                    <input id="edit_category"  class="easyui-textbox" style="width: 200px; height: 30px;" type="text" name="category" data-options="required:true, missingMessage:'请输入活动类型'" />
                </td>
            </tr>
            <tr>
                <td>活动全称:</td>
                <td><input id="edit_title" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="title"/></td>
            </tr>
            <tr>
                <td>活动创建者:</td>
                <td><input id="edit_creator" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="creator"/></td>
            </tr>
            <tr>
                <td>状态:</td>
                <td><input type="radio" id="statusOpen" name="status" value="1" onchange="updateStatus(1)">
                    <label for="statusOpen">开放</label>
                    <input type="radio" id="statusClosed" name="status" value="0" onchange="updateStatus(0)">
                    <label for="statusClosed">关闭</label></td>
            </tr>
            <tr>
                <td>活动摘要:</td>
                <td><input id="edit_abstract" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="abstract"/></td>
            </tr>
            <tr>
                <td>活动详细内容:</td>
                <td><input id="edit_detailed" style="width: 200px; height: 30px;" class="easyui-textbox" type="text" name="detailed"/></td>
            </tr>
            <tr>
                <td>活动开始时间:</td>
                <td><input id="edit_starttime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="starttime"/></td>
            </tr>
            <tr>
                <td>活动结束时间:</td>
                <td><input id="edit_endtime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="endtime"/></td>
            </tr>
            <tr>
                <td>活动归档时间:</td>
                <td><input id="edit_archivedtime" style="width: 200px; height: 30px;" class="easyui-textbox" type="datetime-local" name="archivedtime"/></td>
            </tr>
            <tr>
                <td>相片:</td>
                <td><input onchange="filechange(event)" type="file" name="file" multiple></td>
                <td><div id="imgd"></div></td>
            </tr>
        </table>
    </form>
</div>
<!-- 提交表单处理iframe框架 -->
<iframe id="photo_target" name="photo_target"></iframe>
</body>
</html>